package models

import (
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

type MySQLConf struct {
	Address         string `yaml:"address"`
	DbName          string `yaml:"dbname"`
	Username        string `yaml:"username"`
	Password        string `yaml:"password"`
	MaxOpenConns    int    `yaml:"maxconns"`
	MaxIdleConns    int    `yaml:"maxidleconns"`
	ConnMaxLifetime int64  `yaml:"connmaxlifetime"`
}

var db *gorm.DB

func InitDataBase(dbConf MySQLConf) *gorm.DB {
	var err error
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      true,
		},
	)
	db, err = gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		dbConf.Username,
		dbConf.Password,
		dbConf.Address,
		dbConf.DbName)), &gorm.Config{
		//SkipDefaultTransaction: true,为了确保数据一致性，GORM 会在事务里执行写入操作（创建、更新、删除）。如果没有这方面的要求，您可以在初始化时禁用它。
		NamingStrategy: schema.NamingStrategy{ //GORM 允许用户通过覆盖默认的命名策略更改默认的命名约定，这需要实现接口 Namer
			TablePrefix:   "t_", // 表名前缀，`User` 的表名应该是 `t_users`
			SingularTable: true, // 使用单数表名，启用该选项，此时，`User` 的表名应该是 `t_user`
		},
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}

	db.Debug()
	sqlDB, err := db.DB()
	sqlDB.SetMaxIdleConns(dbConf.MaxIdleConns)
	sqlDB.SetMaxOpenConns(dbConf.MaxOpenConns)
	sqlDB.SetConnMaxLifetime(time.Duration(dbConf.ConnMaxLifetime * int64(time.Millisecond)))
	err = db.AutoMigrate(&User{}, &ContentDetail{})
	if err != nil {
		panic(err)
	}
	log.Println("models.Setup database success!")
	return db
}
func ConnRdb() *redis.Client {
	// redis-cli
	rdb := redis.NewClient(&redis.Options{
		Addr:     "159.75.92.211:16379",
		Password: "12345678", // no password set
		DB:       0,          // use default DB
	})
	_, err := rdb.Ping(context.Background()).Result()
	if err != nil {
		panic(err)
	}
	return rdb
}
